package logic

import (
	"context"
	"encoding/json"
	"login/models/cache"
	"login/models/mysql"
	"time"

	"login/loginrpc/internal/svc"
	"login/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserLogic {
	return &ListUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListUserLogic) ListUser(in *loginrpc.ListUserRequest) (*loginrpc.ListUserResponse, error) {
	// todo: add your logic here and delete this line
	var user []mysql.User

	result, _ := cache.Rdb.Get(l.ctx, "userList").Result()
	if result == "" {

		if in.Name != "" {
			mysql.DB.Debug().Where("name = ?", in.Name).Find(&user)
		}
		mysql.DB.Debug().Find(&user)

		marshal, _ := json.Marshal(user)
		cache.Rdb.Set(l.ctx, "userList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var userList []*loginrpc.ListUser
	for _, m := range user {
		list := loginrpc.ListUser{
			Name:     m.Name,
			Password: m.Password,
			Email:    m.Email,
			Id:       int64(m.ID),
		}
		userList = append(userList, &list)
	}

	return &loginrpc.ListUserResponse{List: userList}, nil
}
